<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="referrer" content="no-referrer">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>网络收藏夹|日程</title>
    <link rel="icon" href="favicon.ico" type="image/x-icon"/>
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>
    <link rel="stylesheet" href="layui/css/layui.css">
    <style type="text/css">


			/* 解决弹出框中select显示难看 */
            .to-fix-select .layui-layer-content {
                overflow: visible !important;
            }

			.home-icon {
				width: 30px;
				height: 30px;
				margin-top: 16px;
				margin-left: 20px;
				cursor: pointer;
			}

			.header {
			    position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 60px;
                background-color: #0A0E11;
			}

			.center {
			    position: fixed;
                width: 100%;
                top: 60px;
                bottom: 44px;
                overflow: auto;
			}

			.footer {
			    position: fixed;
                bottom: 0;
                width: 100%;
                text-align: center;
                height: 44px;
                line-height: 44px;
                background-color: #f5f7fa;
			}

			#logout {
                margin-top: 20px;
                margin-right: 20px;
                float: right;
			}

			.week-list {
				display: flex;
			}

			.week-item {
				width: calc(100% / 7);
				height: 38px;
				line-height: 38px;
				text-align: center;
				border-bottom: 1px solid #ebeef5;
				border-right: 1px solid #ebeef5;
			}

			.week-item:last-child {
                border-right: none;
			}

			.main {
				margin: 30px auto;
                width: 98%;
                max-width: 1680px;
			}

			.day-list {
				display: flex;
			}

			.day-item {
				position: relative;
				width: calc(100% / 7);
				height: 140px;
				line-height: 140px;
				text-align: center;
				border-bottom: 1px solid #ebeef5;
				border-right: 1px solid #ebeef5;
				cursor: pointer;
			}

			.day-item:last-child {
                border-right: none;
			}

			.day-item .task-count {
				position: absolute;
				bottom: 4px;
                left: 4px;
                line-height: initial;
			}

			.day-list:last-child .day-item {
			    border-bottom: none;
			}

			.task-count .layui-badge {
			    margin-right: 2px;
			}

			.task-view {
				position: absolute;
				width: 300px;
				background-color: #fff;
				line-height: 30px;
				display: none;
				z-index: 9999;
				border: 1px solid #EBEEF5;
                padding: 0 10px;
                border-radius: 4px;
                box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
			}

			.task-item {
				display: flex;
				padding: 10px;
				position: relative;
			}

			.task-item .clock {
				margin-right: 10px;
				color: #ccc;
			}

			.task-item .time {
				margin-right: 10px;
			}

			.task-item .content {
				text-align: left;
                word-break: break-all;
                white-space: pre-line;
                flex: 1;
			}

			.task-item .task-action {
			    position: absolute;
                bottom: 4px;
                right: 0;
			}

			.task-item .task-action .layui-btn {
			    height: 18px;
                line-height: 18px;
			}

			.calendar-header {
				margin-bottom: 20px;
                margin-top: 10px;
                display: flex;
                justify-content: center;
                align-items: center;
			}

			.calendar-header .layui-icon {
				color: #009688;
				cursor: pointer;
			}

			.calendar-header .left,
			.calendar-header .right {
				display: inline-block;
				padding: 4px 6px;
				vertical-align: middle;
				font-size: 1.3rem;
			}

			.date-input {
				background-color: #009688;
				border-radius: 4px;
				height: 30px;
				width: 200px;
				margin: 0 10px;
				transition: all .3s;
			}

			.date-input:hover {
			    opacity: .8;
			}

			.date-input input {
				background: transparent;
				border: none;
				text-align: center;
				color: #fff;
				padding: 0;
				height: 30px;
				line-height: 30px;
				cursor: pointer;
			}

			.date-input span {
				position: absolute;
				top: 6px;
				right: 10px;
				color: #fff !important;
			}

			.task-new-mask {
				position: absolute;
				width: 100%;
				height: 100%;
				background-color: #fff;
				top: 0;
				left: 0;
				display: none;
				z-index: 1;
			}

			.day-item:hover .task-new-mask {
				display: block;
			}

			.task-header {
				color: #1e9fff;
				font-weight: bold;
				margin-top: 10px;
				border-bottom: 1px solid #1e9fff;
			}

			.task-level {
				top: 6px;
				margin-right: 6px;
				flex: 0 0 auto;
			}

			.task-list {
				max-height: 300px;
				overflow: auto;
				margin: 10px 0;
			}

			#taskForm {
				padding-top: 10px;
				padding-right: 40px;
			}

			.day-today .date {
				border-radius: 50%;
                background-color: #009688;
                color: #fff;
                width: 3em;
                height: 3em;
                display: inline-block;
                line-height: 3em;
			}

			.date {
				font-size: 1.2em;
				font-weight: bold;
			}

			.lunar {
				position: absolute;
				right: 8px;
				bottom: 4px;
				display: block;
				line-height: initial;
				color: #ccc;
			}

			.calendar-table {
			    margin-bottom: 70px;
			    border-radius: 4px;
			    border: 1px solid #ebeef5;
			}

			.last-month,.next-month {
			    color: #ccc;
			}

			.task-history {
			    position: absolute;
                top: 8px;
                right: 4px;
			}

			.holiday {
                position: absolute;
                top: 8px;
                left: 8px;
                height: 18px;
                line-height: 18px;
                color: #5fb878;
            }

			.alarm-icon {
			    width: 16px;
                height: 16px;
                margin-right: 10px;
                vertical-align: top;
                margin-top: 3px;
			}


    </style>
</head>
<body>
<div class="header">
    <a href="index.html"><img class="home-icon" src="images/home.svg" alt=""></a>
    <button class="layui-btn layui-btn-xs" type="button" id="logout">退出</button>
</div>
<div class="center" id="center">
    <div class="main" id="main">
        <div class="calendar-header">
            <span id="leftBtn" style="transform:rotate(180deg);" class="layui-icon layui-icon-triangle-r left"></span>
            <div class="layui-inline date-input">
                <input type="text" class="layui-input" id="calendarInput" readonly="readonly">
                <span class="layui-icon layui-icon-triangle-d"></span>
            </div>
            <span id="rightBtn" class="layui-icon layui-icon-triangle-r right"></span>
        </div>
        <div id="calendar"></div>
    </div>
</div>
<div class="footer">
    © 2020 网络收藏夹 || 网络收藏夹版权所有
</div>
<form class="layui-form" action="" id="taskForm" lay-filter="taskForm" style="display: none;">
    <input type="hidden" name="taskDate" id="taskDate">
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">日程内容</label>
        <div class="layui-input-block">
            <textarea name="content" required lay-verify="required|length" placeholder="请输入日程内容..."
                      class="layui-textarea" wrap="hard"></textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">事件等级</label>
        <div class="layui-input-block">
            <input type="radio" name="level" value="3" title="待办" checked>
            <input type="radio" name="level" value="2" title="重要">
            <input type="radio" name="level" value="1" title="优先">
            <input type="radio" name="level" value="0" title="紧急">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">邮件提醒</label>
        <div class="layui-input-block">
            <input type="checkbox" id="isAlarm" name="isAlarm" lay-filter="isAlarm" lay-skin="switch" value="1">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">提醒时间</label>
        <div class="layui-input-block">
            <select name="alarmTime" id="alarmTime" lay-filter="alarmTime">
                <option value="">请选择时间</option>
                <option value="08:00">08:00</option>
                <option value="08:30">08:30</option>
                <option value="09:00">09:00</option>
                <option value="09:30">09:30</option>
                <option value="10:00">10:00</option>
                <option value="10:30">10:30</option>
                <option value="11:00">11:00</option>
                <option value="11:30">11:30</option>
                <option value="12:00">12:00</option>
                <option value="12:30">12:30</option>
                <option value="13:00">13:00</option>
                <option value="13:30">13:30</option>
                <option value="14:00">14:00</option>
                <option value="14:30">14:30</option>
                <option value="15:00">15:00</option>
                <option value="15:30">15:30</option>
                <option value="16:00">16:00</option>
                <option value="16:30">16:30</option>
                <option value="17:00">17:00</option>
                <option value="17:30">17:30</option>
                <option value="18:00">18:00</option>
                <option value="18:30">18:30</option>
                <option value="19:00">19:00</option>
                <option value="19:30">19:30</option>
                <option value="20:00">20:00</option>
                <option value="20:30">20:30</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="saveTaskBtn">立即提交</button>
            <button type="button" class="layui-btn layui-btn-primary" id="cancelSaveTaskBtn">取消</button>
        </div>
    </div>
</form>
<script src="layui/jquery-3.1.1.min.js" type="text/javascript" charset="utf-8"></script>
<script src="layui/calendar.js"></script>
<script src="layui/layui.js"></script>
<script>
    layui.use(['layer', 'form', 'laydate', 'flow'], function() {
        var layer = layui.layer;
        var form = layui.form;
        var laydate = layui.laydate;
        var flow = layui.flow;

        var indexMap = new Map();// 弹出层索引容器

        // jQuery全局拦截器
        $(document).ajaxSuccess(function(event,xhr,options){
            var result = xhr.responseJSON;
            if(result != undefined && result.code == "401"){
                window.location.href= "login.html";
            }
        });

        laydate.render({
            elem: '#calendarInput',
            type: 'month',
            format: 'yyyy年MM月',
            value: new Date(),
            min: '1970-01-01',
            max: '2970-12-31',
            btns: ['now','confirm'],
            done: function(value, date, endDate) {
                var text = value.substring(0, 4) + '-' + value.substring(5, 7);
                drawCalender(text);
            }
        });

        // 获取某月第一天是星期几
        window.getFirstDayWeekDay = function(text) { // 2021-12
            var split = text.split('-');
            var d = new Date(parseInt(split[0]), parseInt(split[1]) - 1, 1);
            d.setDate(1);
            return d.getDay();
        };

        // 获取某月有多少天
        window.getCurrMonthDays = function(text) { // 2021-12
            var split = text.split('-');
            var d = new Date(parseInt(split[0]), parseInt(split[1]), 0);
            return d.getDate();
        };

        // 获取上个月有多少天
        window.getPreMonthDays = function(text) { // 2021-12
            var split = text.split('-');
            var d = new Date(parseInt(split[0]), parseInt(split[1]) - 1, 1);
            if (d.getMonth() == 0) {
                d.setFullYear(d.getFullYear() - 1);
                d.setMonth(11);
            } else {
                d.setMonth(d.getMonth() - 1);
            }
            return new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate();
        };

        // 获取上一个月
        window.getPreMonth = function(text) { // 2021-12
            var split = text.split('-');
            var d = new Date(parseInt(split[0]), parseInt(split[1]) - 1, 1);
            if (d.getMonth() == 0) {
                d.setFullYear(d.getFullYear() - 1);
                d.setMonth(11);
            } else {
                d.setMonth(d.getMonth() - 1);
            }
            return d.getFullYear() + '-' + (d.getMonth() + 1 < 10 ? '0' : '') + (d.getMonth() + 1);
        };

        // 获取下一个月
        window.getNextMonth = function(text) { // 2021-12
            var split = text.split('-');
            var d = new Date(parseInt(split[0]), parseInt(split[1]) - 1, 1);
            if (d.getMonth() == 11) {
                d.setFullYear(d.getFullYear() + 1);
                d.setMonth(0);
            } else {
                d.setMonth(d.getMonth() + 1);
            }
            return d.getFullYear() + '-' + (d.getMonth() + 1 < 10 ? '0' : '') + (d.getMonth() + 1);
        };

        // 获取今天日期
        window.getToday = function() {
            var now = new Date();
            return now.getFullYear() + '-' + (now.getMonth() + 1 < 10 ? '0' : '') + (now.getMonth() + 1) + '-' + (now.getDate() <
                10 ?
                '0' :
                '') + now.getDate()
        };

        // 获取农历
        window.getLunar = function(text) { // 2020-01-11
            var split = text.split("-");
            var lunar = calendar.solar2lunar(split[0], split[1], split[2]);
            return lunar;
        };

        window.isHoliday = function(lunar) {
            var cArr = ['1-1','1-2','1-3','4-5','5-1','5-2','5-3','10-1','10-2','10-3','10-4','10-5','10-6','10-7'];
            var lArr = ['12-30','1-1','1-2','1-3','1-4','1-5','1-6','5-5','8-15'];
            return cArr.indexOf(lunar.cMonth + '-' + lunar.cDay) > -1 || lArr.indexOf(lunar.lMonth + '-' + lunar.lDay) > -1;
        };

        // 日期比较
        window.dateCompare = function(text1,text2){ // 2020-01-11
            var time1 = new Date(text1.replace(/-/g, "/")).getTime();
            var time2 = new Date(text2.replace(/-/g, "/")).getTime();
            return time1 - time2;
        }

        window.getLabel = function(level){
            var html = '';
            switch(level) {
                case 0:
                    html = '<span class="layui-badge task-level">紧急</span>';
                    break;
                case 1:
                    html = '<span class="layui-badge layui-bg-orange task-level">优先</span>';
                    break;
                case 2:
                    html = '<span class="layui-badge layui-bg-cyan task-level">重要</span>';
                    break;
                case 3:
                    html = '<span class="layui-badge layui-bg-blue task-level">待办</span>';
                    break;
                case 4:
                    html = '<span class="layui-badge layui-bg-gray task-level">完成</span>';
                    break;
                case 5:
                    html = '<span class="layui-badge-rim task-level">取消</span>';
                    break;
                default:
            }
            return html;
        };

        // 加载数据
        window.loadDataList = function(text){// 2020-09
            layer.load();
            $.ajax({
                type: "GET",
                url: "task/all/" + text,
                dataType: "json",
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    layer.closeAll('loading');
                    if (result.code == 0) {
                        var today = getToday();// 获取今天日期，与任务日期比较，判断是历史任务还是未来任务。
                        $(result.data).each(function(index,item){
                            var html = '';
                            var date = item.date;
                            if(dateCompare(date,today) >= 0){// 未来任务，显示任务个数
                                html += '<div class="task-count">';
                                if(item.blueTasks && item.blueTasks > 0){
                                    html += '<span class="layui-badge layui-bg-blue">' + item.blueTasks + '</span>';
                                }
                                if(item.greenTasks && item.greenTasks > 0){
                                    html += '<span class="layui-badge layui-bg-cyan">' + item.greenTasks + '</span>';
                                }
                                if(item.orangeTasks && item.orangeTasks > 0){
                                    html += '<span class="layui-badge layui-bg-orange">' + item.orangeTasks + '</span>';
                                }
                                if(item.redTasks && item.redTasks > 0){
                                    html += '<span class="layui-badge layui-bg-red">' + item.redTasks + '</span>';
                                }
                                if(item.grayTasks && item.grayTasks > 0){
                                    html += '<span class="layui-badge layui-bg-gray">' + item.grayTasks + '</span>';
                                }
                                if(item.cancelTasks && item.cancelTasks > 0){
                                    html += '<span class="layui-badge-rim">' + item.cancelTasks + '</span>';
                                }
                                html += '</div>';
                            }else{// 历史任务，显示历史图标
                                html += '<span class="layui-badge layui-bg-gray task-history">历史</span>';
                            }
                            // 监听日历hover事件，初始化任务面板
                            $("#" + date).append(html).hover(function(){
                                var taskView = $(this).find('.task-view');
                                if(!taskView[0]){
                                    // 创建任务面板
                                    var html = '';
                                    html += '<div class="layui-anim layui-anim-fadein task-view">';
                                    html += '   <div class="task-header">';
                                    html += '	    <span>' + date + '</span>';
                                    html += '	</div>';
                                    html += '	<div class="task-list" id="task' + date + '">';
                                    html += '   </div>';
                                    html += '   <div class="layui-btn-container">';
                                    if(dateCompare(date,today) >= 0){
                                        html += '   <button type="button" class="layui-btn layui-btn-sm" onclick="addTask(\'' + item.date + '\')">新增日程</button>';
                                    }else{
                                        html += '   <button type="button" class="layui-btn layui-btn-normal layui-btn-sm" onclick="cleanTask(\'' + item.date + '\')">清除历史</button>';
                                    }
                                    html += '   </div>';
                                    html += '</div>';
                                    taskView = $(this).append(html).find('.task-view');
                                    // 初始化数据
                                    flow.load({
                                        elem: '#task' + date
                                        ,scrollElem: '#task' + date
                                        ,mb: 50
                                        ,end: ' '
                                        ,done: function(page, next){
                                          var lis = [];
                                          $.ajax({
                                            type: "GET",
                                            url: "task/list",
                                            data: {"date": date, "pageNum": page,"pageSize": 20},
                                            dataType: "json",
                                            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                                            success: function (result) {
                                                if (result.code == 0) {
                                                    $(result.data.list).each(function(i,t){
                                                        var html = '';
                                                        html += '   <div class="task-item">';
                                                        html += getLabel(t.level);
                                                        html += '	    <span class="content">' + t.content + '</span>';
                                                        if(t.level < 4){
                                                            html += '   <div class="layui-btn-container task-action" data-id="' + t.id + '">';
                                                            if(t.isAlarm){
                                                                html += '   <img class="alarm-icon" src="images/alarm.svg" data-time="' + t.alarmTime.substring(11) + '">';
                                                            }
                                                            html += '       <button type="button" class="layui-btn layui-btn-xs layui-btn-normal" onclick="doTask(this)">完成</button> ';
                                                            if(dateCompare(date,today) >= 0){
                                                                html += '   <button type="button" class="layui-btn layui-btn-xs layui-btn-danger" onclick="deleteTask(this)">删除</button> ';
                                                            }else{
                                                                html += '   <button type="button" class="layui-btn layui-btn-xs layui-btn-primary" onclick="cancelTask(this)">取消</button> ';
                                                            }
                                                            html += '   </div>';
                                                        }
                                                        html += '   </div>';
                                                        lis.push(html);
                                                    });
                                                    next(lis.join(''), page < result.data.pages);
                                                }
                                            }
                                          });
                                        }
                                    });
                                }
                                // 初始化面板后，计算面板显示位置
                                var tWidth = parseInt(taskView.width());
                                var tHeight = parseInt(taskView.height());
                                var top = $(this).offset().top;
                                var left = $(this).offset().left;
                                var width = parseInt($(this).width());
                                var height = parseInt($(this).height());
                                var mWidth = parseInt($("#main").width());
                                var mHeight = parseInt($("#main").height());
                                // 任务面板初始位置是下，计算固定显示位置
                                var bool1 = top + height + tHeight > mHeight;// 判断垂直方向
                                var bool2 = left + tWidth > mWidth;// 判断水平方向
                                if(bool1 && bool2){
                                    taskView.css("bottom", height);
                                    if(top - tHeight < 0) {
                                        taskView.css("bottom", height - (tHeight - top));
                                    }
                                    taskView.css("right", width);
                                    if(left - tWidth < 0) {
                                        taskView.css("right", width - (tWidth - left));
                                    }
                                }else if(bool1){
                                    taskView.css("bottom", height);
                                    if(top - tHeight < 0) {
                                        taskView.css("bottom", height - (tHeight - top));
                                    }
                                }else if(bool2){
                                    taskView.css("right", width);
                                    if(left - tWidth < 0) {
                                        taskView.css("right", width - (tWidth - left));
                                    }
                                    taskView.css("bottom", 0);
                                }
                                taskView.show();
                            },function(){
                                $(this).find('.task-view').hide();
                            }).find(".task-new-mask").remove();// 移除添加任务按钮：如果是历史时间，不需要按钮。如果是未来时间且有任务，则在任务面板添加。所以这里不需要。
                            // 监听闹钟hover事件
                            var tipIndex;
                            $("#" + date).on('mouseenter','.alarm-icon',function(e){
                                var that = $(e.target);
                                tipIndex = layer.tips(that.attr("data-time"), that, {tips: 4});
                            }).on('mouseleave','.alarm-icon',function(e){
                                layer.close(tipIndex);
                            });
                        });
                    } else {
                        layer.msg("数据加载失败", {icon: 5});
                    }
                }
            });
        };

        // 画日历
        window.drawCalender = function(text) { // 2021-12
            if (!text) {
                var now = new Date();
                text = now.getFullYear() + '-' + (now.getMonth() + 1 < 10 ? '0' : '') + (now.getMonth() + 1);
            }
            // 获取当前月份第一天星期几
            var firstDayWeekDay = getFirstDayWeekDay(text);
            // 获取当前月份有多少天
            var currMonthDays = getCurrMonthDays(text);
            // 获取上月有多少天
            var preMonthDays = getPreMonthDays(text);
            var currMonthCount = 1;
            var currMonthBlock = firstDayWeekDay + currMonthDays - 1;
            var nextMonthCount = 1;
            var currMonth = text;
            var preMonth = getPreMonth(text);
            var nextMonth = getNextMonth(text);
            var today = getToday();
            // 画格子
            var html = '';
            html += '<div class="week-list">';
            html += '	<div class="week-item">星期日</div>';
            html += '	<div class="week-item">星期一</div>';
            html += '	<div class="week-item">星期二</div>';
            html += '	<div class="week-item">星期三</div>';
            html += '	<div class="week-item">星期四</div>';
            html += '	<div class="week-item">星期五</div>';
            html += '	<div class="week-item">星期六</div>';
            html += '</div>';
            for (var i = 0; i < 6; i++) {
                html += '<div class="day-list">';
                for (var j = 0; j < 7; j++) {
                    html += '	<div class="day-item">';
                    html += '		<span class="date"></span>';
                    html += '		<span class="lunar"></span>';
                    html += '	</div>';
                }
                html += '</div>';
            }
            $("#calendar").addClass("calendar-table").empty().append(html);
            // 填数据
            var nowDay = parseInt(today.substring(8));
            var nowMonth = today.substring(0,7);
            $('#calendar .day-item').each(function(index) {
                var day;
                if (index < firstDayWeekDay) {
                    var num = preMonthDays - (firstDayWeekDay - index - 1);
                    day = preMonth + '-' + (num < 10 ? '0' : '') + num;
                    $(this).attr("id", day).addClass('last-month').find('.date').text(num);
                } else if (index >= firstDayWeekDay && index <= currMonthBlock) {
                    day = currMonth + '-' + (currMonthCount < 10 ? '0' : '') + currMonthCount;
                    // 过去 现在 未来
                    var c = '';
                    var value = dateCompare(day,today);
                    if(value < 0){
                        c = 'day-before';
                    }else if(value === 0){
                        c = 'day-today';
                    }else {
                        c = 'day-after';
                    }
                    $(this).attr("id", day).addClass(c).find('.date').text(currMonthCount);
                    currMonthCount++;
                } else {
                    day = nextMonth + '-' + (nextMonthCount < 10 ? '0' : '') + nextMonthCount;
                    $(this).attr("id", day).addClass('next-month').find('.date').text(nextMonthCount);
                    nextMonthCount++;
                }
                // 农历
                var lunar = getLunar(day);
                $(this).find(".lunar").text(lunar.IDayCn === "初一" ? lunar.IMonthCn : lunar.IDayCn);
                // 节假日
                if(isHoliday(lunar)) $(this).append('<span class="holiday">假</span>');
            });
            // 给今天和明天添加新增日程按钮
            $(".day-item.day-after,.day-item.day-today").each(function(){
                var d = $(this).attr("id");
                var html = '';
                html += '<div class="layui-anim layui-anim-fadein task-new-mask">';
                html += '	<button type="button" class="layui-btn layui-btn-sm" onclick="addTask(\''+ d +'\')">新增日程</button>';
                html += '</div>';
                $(this).append(html);
            });
            // 请求后端数据
            loadDataList(text);
        };

        drawCalender();

        // 邮件提醒开关
        form.on('switch(isAlarm)', function(data){
            if(data.elem.checked){
                $("#alarmTime").attr("lay-verify","required");
            }else{
                $("#alarmTime").removeAttr("lay-verify");
            }
        });

        form.verify({
          length: function (value, item) {
            if(value.length>500){
                return '最多输入500个字符';
            }
          }
        });

        $("#leftBtn").click(function() {
            var date = $("#calendarInput").val();
            var preMonth = getPreMonth(date.substring(0, 4) + '-' + date.substring(5, 7));
            var split = preMonth.split("-");
            if(split[0] < 1970){
                return false;
            }
            $("#calendarInput").val(split[0] + "年" + split[1] + "月");
            drawCalender(preMonth);
        });

        $("#rightBtn").click(function() {
            var date = $("#calendarInput").val();
            var nextMonth = getNextMonth(date.substring(0, 4) + '-' + date.substring(5, 7));
            var split = nextMonth.split("-");
            if(split[0]> 2970){
                return false;
            }
            $("#calendarInput").val(split[0] + "年" + split[1] + "月");
            drawCalender(nextMonth);
        });

        form.on('select(alarmTime)', function(data){
          if(data.value && !$("#isAlarm").is(':checked')){
            $("#isAlarm").prop("checked", true);
            form.render('checkbox', 'taskForm');
          }
        });

        // 监听提交
        form.on('submit(saveTaskBtn)', function(data) {
            var postData = data.field;
            if(postData.isAlarm && postData.alarmTime){
                postData.alarmTime = postData.taskDate + ' ' + postData.alarmTime + ':00';
            }else{
                postData.alarmTime = "";
            }
            layer.load();
            $.ajax({
                type: "POST",
                url: "task",
                data: JSON.stringify(postData),
                contentType: 'application/json;charset=utf-8',
                dataType: "json",
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    layer.closeAll('loading');
                    layer.close(indexMap.get('#taskForm'));
                    if (result.code == 0) {
                        window.location.reload();
                    } else {
                        layer.msg("添加失败", {icon: 5});
                    }
                }
            });
            return false;
        });

        // 新增日程点击事件
        window.addTask = function(text){// 2020-01-01
            $('#taskForm')[0].reset();

            $("#taskDate").val(text);

            var index = layer.open({
                type: 1,
                skin: 'to-fix-select',
                content: $('#taskForm')
            });
            indexMap.set('#taskForm',index);
        };

        // 清除任务
        window.cleanTask = function(text){
            layer.confirm('确认清除历史任务吗？', function(index){
                layer.close(index);

                 $.ajax({
                    type: "GET",
                    url: "task/clean/" + text ,
                    dataType: "json",
                    headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                    success: function (result) {
                        if (result.code == 0) {
                            layer.msg('操作成功', {icon: 6});
                            $("#task"+text).empty();
                        } else {
                            layer.msg('操作失败', {icon: 5});
                        }
                    }
                });
            });
        };

        // 完成任务
        window.doTask = function(obj){
            var id = $(obj).parent().attr("data-id");
            $.ajax({
                type: "GET",
                url: "task/done/" + id ,
                dataType: "json",
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    if (result.code == 0) {
                        var task_item = $(obj).parent().parent();
                        layer.msg('操作成功', {icon: 6});
                        task_item.find('.task-level').replaceWith('<span class="layui-badge layui-bg-gray task-level">完成</span>');
                        task_item.find('.task-action').remove();
                    } else {
                        layer.msg('操作失败', {icon: 5});
                    }
                }
            });
        };

        // 取消任务
        window.cancelTask = function(obj){
            var id = $(obj).parent().attr("data-id");
            $.ajax({
                type: "GET",
                url: "task/cancel/" + id ,
                dataType: "json",
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    if (result.code == 0) {
                        var task_item = $(obj).parent().parent();
                        layer.msg('操作成功', {icon: 6});
                        task_item.find('.task-level').replaceWith('<span class="layui-badge-rim task-level">取消</span>');
                        task_item.find('.task-action').remove();
                    } else {
                        layer.msg('操作失败', {icon: 5});
                    }
                }
            });
        };

        // 删除任务
        window.deleteTask = function(obj){
            var id = $(obj).parent().attr("data-id");
            $.ajax({
                type: "GET",
                url: "task/delete/" + id ,
                dataType: "json",
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    if (result.code == 0) {
                        layer.msg('删除成功', {icon: 6});
                        $(obj).parent().parent().remove();
                    } else {
                        layer.msg('删除失败', {icon: 5});
                    }
                }
            });
        };

        $("#cancelSaveTaskBtn").click(function(){
            layer.close(indexMap.get('#taskForm'));
        });

        // 登出
        $("#logout").click(function () {
            layer.confirm('确认退出系统吗？', function(index){
                layer.close(index);

                localStorage.clear();
                window.location.href = "login.html";
            });
        });

    });


</script>
</body>
</html>
